﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NTQOnlineExam.Services.Infrastructure;
using NTQOnlineExam.Services.Models;

namespace NTQOnlineExam.Services.ReportService.Order
{


    public class GetOrderDetailByOrderIdDbCommand : ICommand<IList<OrderDetailDTO>>
    {
        private readonly Guid _orderId;

        public GetOrderDetailByOrderIdDbCommand(Guid orderId)
        {
            _orderId = orderId;
        }

        private const string _sql = @"
                SELECT  *
                FROM    [dbo].[OrderDetail]
                WHERE   OrderId = @OrderId
        ";


        public IList<OrderDetailDTO> Execute()
        {
            var connectionString = ConfigurationManager.AppSettings["ConnectionString"];
            using (var connection = new SqlConnection(connectionString))
            {
                var list = new List<OrderDetailDTO>();;
                var cmd = new SqlCommand(_sql, connection);
                cmd.Parameters.Add("@OrderId", SqlDbType.UniqueIdentifier).Value = _orderId;
                connection.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                try
                {
                    
                        while (reader.Read())
                        {
                            list.Add(GetItemDto(reader));
                        }
                }
                finally
                {
                    reader.Close();
                }
                return list;
            }
        }
        private OrderDetailDTO GetItemDto(SqlDataReader reader)
        {
            return new OrderDetailDTO
            {
                Id = Guid.Parse(reader["Id"].ToString()),
                TermName = reader["TermName"].ToString(),
                Price = reader["Price"] != DBNull.Value ? (decimal.Parse(reader["Price"].ToString())) : 0,
                TermId = (int)reader["TermId"]
            };
        }

    }
}

